﻿using Consul;
using Microsoft.Extensions.Configuration;
using System.Runtime.CompilerServices;

namespace ConsulUtility
{
    public static class ConsulRegister
    {
        public static void ConsulExtend(this IConfiguration config)
        {
            //配置文件参数
            string consulIP = config["Consul:CousulIP"];
            string hostIP = config["Consul:HostIP"];
            int consulPort = 0;
            int.TryParse(config["Consul:Port"], out consulPort);
            string healthPath = config["Consul:HealthCheck"];
            string hostName = config["Consul:HostName"];
            //Consul
            ConsulClient client = new ConsulClient(x =>
            {
                //目标服务器
                x.Address = new Uri($"http://{consulIP}:8500/");
                x.Datacenter = "dc1";
            });
            //本机
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = Guid.NewGuid().ToString(),
                Name = hostName,
                Address = hostIP,
                Port = consulPort,
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(3),
                    HTTP = $"http://{hostIP}:{consulPort}{healthPath}",
                    Timeout = TimeSpan.FromSeconds(6),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(6)
                }
            });
        }
    }
}
